<template>
	<view class="content">
		<view class="titleView">
			<text>您好,</text>
			<text>欢迎使用免烦脑</text>
		</view>
		<view class="phone" style="margin-top: 69rpx;">
			<input class="inputPhone" type="number" placeholder="请输入手机号" placeholder-class="phonePlaceSytle"
				v-model="telNum" @blur="checkPhoneNum" maxlength="11" />
			<image v-if="telNum" src="../../static/image/icon_clear.png" @click="clearInput()"></image>
		</view>
		<view v-if="isVerifyLogin" class="phone" style="margin-top: 24rpx;">
			<input class="inputPhone" type="number" placeholder="请输入验证码" placeholder-class="phonePlaceSytle"
				maxlength="4" v-model="verifCode" />
			<text class="getCode" v-if="!sendMsgDisabled" @click="getloginCode()">获取验证码</text>
			<text class="getCode" v-else>{{ codeTime }}秒后重新获取</text>
		</view>

		<view v-else class="phone" style="margin-top: 24rpx;">
			<input class="inputPhone" type="text" placeholder="请输入密码" placeholder-class="phonePlaceSytle" maxlength="16"
				v-model="secret" />
			<image v-if="secret" src="../../static/image/icon_clear.png" @click="clearInputSecret()"></image>
		</view>
		<!-- 提示文字 -->
		<view class="hint"><text v-text="checkText"></text></view>
		<view class="loginBtn flex-c" :class="'loginBtn-' + animation" @click="login()"><text>登录</text></view>
		<view class="protocolView">
			<view class="protocolContent">
				<image v-if="!isAgree" src="../../static/image/login/dot.png" style="width: 26rpx;height: 26rpx;"
					@click="agreeReadProtocol()"></image>
				<image v-if="isAgree" src="../../static/image/login/dot_select.png" style="width: 26rpx;height: 26rpx;"
					@click="agreeReadProtocol()"></image>
				<text class="Tips1" style="margin-left: 10rpx;" @click="agreeReadProtocol()">登录注册即表示您已阅读并同意易爱</text>
				<text class="Tips2" @click="toUserProtocol()">《用户协议》</text>
				<text class="Tips1">及</text>
				<text class="Tips2" @click="toPrivacyPolicy()">《隐私政策》</text>
			</view>
			<view v-if="isShowTips" class="tipArrow content">
				<text>请先阅读并勾选用户协议</text>
			</view>
		</view>

		<!-- <image src="../../static/image/login/img_otherLogin.png" style="margin-top: 200rpx;width: 263rpx;height: 20rpx;"></image> -->
		<!-- <image class="icon_wechat" src="../../static/image/login/icon_wechat.png"></image> -->

		<view class="bottomView">
			<text class="noLogin" @click="noWayLogin()">无法登录</text>
			<view style="width: 4rpx;height: 40rpx;background-color: #666666;"></view>
			<text v-show="isVerifyLogin" class="noLogin" @click="loginType(false)">密码方式登录</text>
			<text v-show="!isVerifyLogin" class="noLogin" @click="loginType(true)">短信方式登录</text>
		</view>

		<!-- 无法登录，拨打客服电话 -->
		<uni-popup ref="popup1" :mask-click="false" :safe-area="false" type="dialog">
			<view class="popup1">
				<text class="popup1_t1">提示</text>
				<text class="popup1_t2">是否需要拨打客服热线</text>
				<view class="popup1_bottom">
					<view class="content popup1_bottom_item" @click="cancel()">取消</view>
					<view class="columnLine"></view>
					<view class="content popup1_bottom_item" @click="enter()">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	const app = getApp();
	import * as api from '@/api/login';
	import {
		isNull
	} from '@/utils/utils.js';
	import store from '@/store';
	export default {
		data() {
			return {
				telNum: '',
				checkText: '', //提示性文字
				isVerifyLogin: true, //是否通过验证码方式登录
				verifCode: '', //验证码
				getCodeText: '获取验证码',
				phoneReg: new RegExp(/^1[3-9]\d{9}$/), //手机号正则验证
				sendMsgDisabled: false,
				codeTime: 59,
				secret: '',
				isShowTips: false,
				UUID: '', //本机的UUID 
				isAgree: false, //是否同意协议
				animation: '' // 动画样式
			};
		},
		onLoad() {
			console.log('onload');
		},
		methods: {
			// 同意并阅读协议
			agreeReadProtocol() {
				this.isAgree = !this.isAgree;
				if (this.isAgree) this.isShowTips = false
			},
			// 监听手机号输入
			checkPhoneNum: function(event) {
				let phoneNum = event.detail.value;
				if (phoneNum.trim().length <= 0) {
					this.checkText = '请输入手机号';
					return;
				} else if (!this.phoneReg.test(phoneNum)) {
					this.checkText = '手机号格式错误';
					return;
				} else {
					this.checkText = '';
				}
			},
			clearInput() {
				this.telNum = '';
			},
			clearInputSecret() {
				this.secret = ''
			},
			// 获取验证码
			getloginCode() {
				let that = this;
				//做非空判断
				let phoneNum = that.telNum;
				if (phoneNum.trim().length <= 0) {
					that.checkText = '请输入手机号';
					return;
				} else if (!that.phoneReg.test(phoneNum)) {
					that.checkText = '手机号格式错误';
					return;
				} else {
					that.checkText = '';
				}
				that.sendMsgDisabled = true;
				// 开始切换文字倒计时
				let codeInterval = setInterval(() => {
					if (that.codeTime-- <= 1) {
						that.codeTime = 59;
						that.sendMsgDisabled = false;
						clearInterval(codeInterval);
					}
				}, 1000);
				//调用接口请求验证码
				api.requestVerify(phoneNum)
					.then(function(res) {
						console.log(res);
						if (res.data.code == 2000) {
							that.$toast('验证码已发送，请查收!', {
								icon: 'none'
							});
						} else {
							that.$toast('验证码错误，请重试!', {
								icon: 'none'
							});
						}
					})
					.catch(function(error) {
						console.log('get verification fail', error);
					});
			},
			// 按钮抖动动画
			startShark() {
				this.animation = 'shake';
				setTimeout(() => {
					this.animation = '';
				}, 1000);
			},
			// 开始登录
			login() {
				if (!this.isAgree) {
					this.startShark();
					this.isShowTips = true
					return;
				}
				let phoneNum = this.telNum;
				if (phoneNum.trim().length <= 0) {
					this.checkText = '请输入手机号';
					return;
				} else if (!this.phoneReg.test(phoneNum)) {
					this.checkText = '手机号格式错误';
					return;
				}
				if (this.isVerifyLogin) {
					if (this.verifCode.trim().length <= 0) {
						this.checkText = '请输入验证码';
						return;
					}
				} else {
					let secret = this.secret;
					if (secret.trim().length <= 0) {
						this.checkText = '请输入密码';
						return;
					} else if (secret.trim().length < 8 || secret.trim().length > 16) {
						this.checkText = '密码格式错误';
						return;
					}
				}
				this.toLogin()
			},
			toLogin() {
				let that = this
				let params = {
					role: 'EiUser',
					uuid: that.$store.state.deviceUUID
				}
				if (this.isVerifyLogin) {
					params.verification = {
						mobile: that.telNum,
						verificationCode: that.verifCode
					}
				} else {
					params.account = that.telNum
					params.secret = that.secret
				}
				let data = {
					action: 'login',
					params,
				};
				console.log('>>>',data);
				api.login(data).then(function(res) {
						console.log('login>>', res);
						if (res.data.code == 2000) {
							let appId = res.data.data.appIdInfo.appId;
							let appSecret = res.data.data.appIdInfo.appSecret;
							let userId = res.data.data.appIdInfo.userId;
							store.commit('token', res.data.data.appIdInfo.token);
							let userInfo = uni.getStorageSync('userInfo');
							if (isNull(userInfo)) {
								// first login
								userInfo = {
									currentUser: {
										userId: userId,
										appId: appId,
										appSecret: appSecret,
										phone: that.telNum
									},
									loginUserList: [{
										userId: userId,
										appId: appId,
										appSecret: appSecret,
										phone: that.telNum
									}]
								};
							} else {
								// agin 将当前登录的用户信息更新到currentUser中去
								userInfo.currentUser = {
									userId: userId,
									appId: appId,
									appSecret: appSecret,
									phone: that.telNum
								};
								let isNewUser = true;
								// 更新用户列表 (已经存在的用户就更新其个人信息 ,新用户则直接添加)
								userInfo.loginUserList.forEach(item => {
									if (item.userId == userId) {
										item.appId = appId;
										item.appSecret = appSecret;
										item.phone = that.telNum;
										isNewUser = false;
									}
								});
								if (isNewUser) {
									userInfo.loginUserList.push(userInfo.currentUser);
								}
							}
							try {
								store.commit('userInfo', userInfo);
								/* 轮询 tokenId */
								app.getTokenIdPolling();
								that.getUserInfo();
							} catch (e) {
								//TODO handle the exception
								console.log('缓存失败', e);
							}
						} else {
							that.checkText = '手机号或密码错误'
						}
					})
					.catch(function(error) {
						console.log('login fail', error);
						that.checkText = '请求出错';
					});
			},
			getUserInfo() {
				let that = this;
				let userId = this.$store.state.userInfo.currentUser.userId;
				let data = {
					userId: userId,
					action: 'getUserInfo'
				};
				//调用接口请求个人信息
				api.getUserInfo(data)
					.then(function(res) {
						console.log('getUserInfo::', res);
						// if(res.data.code == 2001) return;
						if (res.data.message == 'userInfo is null') {
							//用户未填写个人信息  跳
							uni.redirectTo({
								url: 'fillHealhyRecords/noInfo'
							});
						} else {
							that.$store.commit('userBaseInfo',res.data.data)
							uni.switchTab({
								url: '../detection/detection'
							});
						}
					}).catch(function(error) {
						console.log('get userInfo fail', error);
					});
			},
			// 用户协议
			toUserProtocol() {
				console.log('用户协议');
				uni.navigateTo({
					url: '../mine/systemSetting/aboutUs/webView?index=0'
				});
			},
			// 隐私政策
			toPrivacyPolicy() {
				uni.navigateTo({
					url: '../mine/systemSetting/aboutUs/webView?index=1'
				});
			},
			// 无法登录 调用弹窗通知拨打客服电话
			noWayLogin() {
				this.$refs.popup1.open('bottom');
			},
			//通过密码方式登录
			loginType(flag) {
				this.isVerifyLogin = flag
			},
			// 取消拨号
			cancel() {
				this.$refs.popup1.close();
			},
			// 确认拨号
			enter() {
				uni.makePhoneCall({
					phoneNumber: '025-58177188',
					success(res) {
						console.log('success' + res);
					},
					fail(res) {
						console.log('faiil' + res);
					}
				});
			}
		}
	};
</script>

<style>
	@import url('../style/animation.css');

	page {
		background-color: #f5f5f5;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.protocolView {
		margin-top: 50rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.protocolContent {
		display: flex;
		align-items: center;
	}

	.tipArrow {
		align-self: flex-start;
		margin-left: -15rpx;
		margin-top: 15rpx;
		width: 400rpx;
		height: 50rpx;
		background-color: #6c6c6c;
		position: relative;
		border-radius: 12rpx;
	}

	.tipArrow text {
		color: #fff;
		font-size: 24rpx;
	}

	.tipArrow:after {
		content: "";
		position: absolute;
		left: 20rpx;
		top: -9rpx;
		width: 18rpx;
		height: 18rpx;
		/* margin-left: -5px; */
		background-color: #6c6c6c;
		transform: rotate(-45deg);
	}

	.flex-c {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.titleView {
		margin-top: 166rpx;
		width: 700rpx;
		display: flex;
		flex-direction: column;
	}

	.titleView text {
		font-size: 56rpx;
		font-family: Source Han Sans CN;
		font-weight: bold;
		color: #333333;
		margin-left: 15rpx;
	}

	.phone {
		width: 700rpx;
		height: 122rpx;
		background-color: #ffffff;
		border-radius: 15px;
		display: flex;
		align-items: center;
		position: relative;
	}

	.phone image {
		position: absolute;
		width: 35rpx;
		height: 35rpx;
		right: 50rpx;
	}

	.inputPhone {
		margin-left: 45rpx;
		width: 600rpx;
		height: 100%;
	}

	.phonePlaceSytle {
		font-size: 32rpx;
		font-family: Source Han Sans CN;
		font-weight: normal;
		color: #666666;
	}

	.getCode {
		font-size: 32rpx;
		font-family: Source Han Sans CN;
		font-weight: normal;
		color: #0659c7;
		position: absolute;
		right: 18px;
	}

	.hint {
		font-size: 28rpx;
		color: #f6464e;
		height: 20px;
		width: 80%;
		margin-top: 20rpx;
	}

	.loginBtn {
		width: 700rpx;
		height: 100rpx;
		border-radius: 50px;
		background-color: #0659c7;
		/* margin-top: 58rpx; */
	}

	.loginBtn:active {
		background-color: #007aff;
	}

	.loginBtn text {
		font-size: 44rpx;
		font-family: Source Han Sans CN;
		font-weight: normal;
		color: #ffffff;
	}

	.icon_wechat {
		width: 107rpx;
		height: 107rpx;
		margin-top: 45rpx;
	}

	.Tips1 {
		font-size: 24rpx;
		font-family: Source Han Sans CN;
		font-weight: normal;
		color: #666666;
	}

	.Tips2 {
		font-size: 22rpx;
		font-family: Source Han Sans CN;
		font-weight: normal;
		color: #0659c7;
		line-height: 30px;
	}

	.bottomView {
		margin-top: 54rpx;
		margin-bottom: 45rpx;
		width: 300rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.noLogin {
		font-size: 28rpx;
		font-family: Source Han Sans CN;
		font-weight: normal;
		color: #0659c7;
	}

	/* 弹窗 */
	/* popup 底部两个按钮区域 */

	.popup1 {
		margin: auto auto 45rpx;
		width: 700rpx;
		height: 395rpx;
		background-color: white;
		border-radius: 15px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
	}

	.popup1_t1 {
		margin-top: 47rpx;
		font-size: 48rpx;
		font-family: Source Han Sans CN;
		font-weight: bold;
		color: #000000;
	}

	.popup1_t2 {
		font-size: 40rpx;
		font-family: Source Han Sans CN;
		font-weight: normal;
		color: #000000;
	}

	.popup1_bottom {
		width: 100%;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-radius: 0 0 15px 15px;
		border-top: 2rpx solid #dcdcdc;
	}

	.popup1_bottom_item {
		width: 50%;
		height: 100%;
	}

	.popup1_bottom text {
		font-size: 36rpx;
		font-family: Source Han Sans CN;
		font-weight: normal;
		color: #000000;
	}

	.columnLine {
		width: 2rpx;
		height: 100%;
		background-color: #dcdcdc;
	}

	/* 错误抖动动画  */
	.loginBtn-shake {
		animation: shake 0.3s !important;
	}

	@keyframes shake {

		0%,
		100% {
			transform: translateX(0);
		}

		10% {
			transform: translateX(-9px);
		}

		20% {
			transform: translateX(8px);
		}

		30% {
			transform: translateX(-7px);
		}

		40% {
			transform: translateX(6px);
		}

		50% {
			transform: translateX(-5px);
		}

		60% {
			transform: translateX(4px);
		}

		70% {
			transform: translateX(-3px);
		}

		80% {
			transform: translateX(2px);
		}

		90% {
			transform: translateX(-1px);
		}
	}
</style>